<?php
/**
 * User: xialei
 * Date: 2016/7/2 0002
 * Time: 15:23
 */

namespace app\modules\admin\controllers;


use app\commands\CommonTool;
use app\models\User;
use Yii;
use yii\base\UserException;
use yii\rest\Controller;
use yii\web\NotFoundHttpException;

class UserController extends Controller
{
    /**
     * 用户列表
     * @param int $max
     * @param int $size
     * @param string $keyword
     * @return array|\yii\db\ActiveRecord[]
     */
    public function actionList($max = 0, $size = 30, $keyword = '')
    {
        $query = User::find()->orderBy(['createdAt' => SORT_DESC])->limit($size);
        if (!empty($keyword)) {
            $query->andWhere([
                'OR',
                ['like', 'nickname', $keyword],
                ['like', 'realname', $keyword],
                ['like', 'phone', $keyword]
            ]);
        }
        $count = $query->count();
        if ($max > 0) {
            $query->andWhere(['<', 'createdAt', $max]);
        }

        $list = $query->asArray()->all();
        return [
            'count' => $count,
            'list' => $list
        ];
    }

    public function actionView($id)
    {
        $user = User::findOne($id);
        if (empty($user)) {
            throw new NotFoundHttpException('用户不存在');
        }
        return $user;
    }

    public function actionPost($id)
    {
        $user = $this->actionView($id);
        $user->setAttributes(Yii::$app->request->getBodyParams());
        if (!$user->save()) {
            throw new UserException(CommonTool::getFirstError($user));
        }
        return $user;
    }
}